import {
  listCart,
  updateCartApi,
  deleteCartApi,
  createOrders
} from "../../api/order/index"
import {
  showModal,
  showModalCancelAsync
} from "../../utils/modal"
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 选中商品
    result: [],
    // 全选按钮
    all: false,
    // 结算区域
    show: false,
    // 购物车
    list: [],
    // 合计
    totalPay: 0,
    // 定时器: 预定按钮时
    timer: null,
  },

  onLoad() {
    this.setData({
      show: true
    })
    this.getCartList();
  },

  // 获取购物车列表
  getCartList() {
    listCart().then(res => {
      res.rows.forEach(item => {
        item.food.image = app.globalData.resourceUrl + item.food.image;
      })
      this.setData({
        list: res.rows
      })
    }).catch(err => {
      console.log("请求失败", err);
    })
  },

  // 商品多选
  onGoodChange(event) {
    // ["1", "2"]
    // 判断全选按钮状态
    this.setData({
      result: event.detail,
      all: this.data.list.length !== 0 &&
        this.data.list.length === event.detail.length
    });
    // 显示合计金额
    let totalPay = 0;
    this.data.list.forEach(item => {
      // 在 event.detail 选中的
      const strId = item.id + "";
      if (event.detail.includes(strId)) {
        totalPay += item.count * 100 * item.food.unitPrice;
      }
    })
    this.setData({
      totalPay: (totalPay / 100).toFixed(2)
    })
  },

  // 全选按钮
  onAllChange(event) {
    if (event.detail) {
      // 全选
      const ids = this.data.list.map(item => item.id + "");
      let totalPay = 0;
      this.data.list.forEach(item => {
        totalPay += item.count * 100 * item.food.unitPrice;
      })
      this.setData({
        result: ids,
        totalPay: (totalPay / 100).toFixed(2)
      })
    } else {
      this.setData({
        totalPay: 0,
        result: []
      })
    }

    // 更新全选状态
    this.setData({
      all: event.detail
    });
  },

  onStepChange(event) {
    const dataset = event.target.dataset;
    // 找到目标菜品
    this.data.list.forEach(item => {
      if (item.id === dataset.id) {
        // 发起请求
        updateCartApi({
          id: item.id,
          count: event.detail
        }).then(() => {}).catch(() => {})
        item.count = event.detail
      }
    });
    // 更新合计价格
    let totalPay = 0;
    this.data.list.forEach(item => {
      // 在 event.detail 选中的
      const strId = item.id + "";
      if (this.data.result.includes(strId)) {
        totalPay += item.count * 100 * item.food.unitPrice;
      }
    })
    this.setData({
      list: this.data.list,
      totalPay: (totalPay / 100).toFixed(2)
    })
  },

  // 管理菜品：删除
  manageGoods() {
    this.setData({
      show: !this.data.show,
      all: false,
      result: [],
      totalPay: 0
    })
  },

  clickDelFood() {
    showModalCancelAsync("是否删除所选菜品?").then(res => {
      if (res.confirm) {
        this.delFood();
      }
    }).catch(() => {})
  },

  // 删除购物车中的菜品
  delFood() {
    const strIds = this.data.result.join(",");
    deleteCartApi(strIds).then(() => {
      this.setData({
        all: false,
        result: [],
        totalPay: 0,
        show: true
      }, this.getCartList)
    }).catch(() => {})
  },

  // 结算
  submit() {
    // 正在创建订单,防止重复触发
    if (this.data.timer) return;
    if (this.data.totalPay > 0) {
      this.startRequest("创建订单中");
      const submitFoodList = this.data.list.map(item => {
        const obj = {};
        const strId = item.id + "";
        if (this.data.result.includes(strId)) {
          obj["count"] = item.count;
          obj["foodId"] = item.foodId;
        }
        return Object.keys(obj).length > 0 ? obj : undefined;
      }).filter(item => item !== undefined);
      try {
        createOrders(submitFoodList)
          .then(() => {
            // 提交成功, 删除购物车的菜品
            this.delFood();
          })
      } catch (err) {
        console.log("请求失败:", err);
      } finally {
        this.endRequest();
      }
    } else {
      showModal("还没有选择菜品!")
    }
  },

  /**
   * 开始请求
   * @param {string} content 加载框内容
   */
  startRequest(content) {
    const timer = setTimeout(() => {
      wx.showLoading({
        title: content,
        mask: true
      })
    }, 1000);
    this.setData({
      timer: timer
    });
  },

  /**
   * 结束请求
   */
  endRequest() {
    wx.hideLoading();
    clearTimeout(this.data.timer);
    this.setData({
      timer: null
    })
  }
})